package com.wkh.common.app

import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry

class CachedLifecycleRegister(lifecycleOwner: LifecycleOwner) : LifecycleRegistry(lifecycleOwner) {

    private var observers = ArrayList<LifecycleObserver>()

    fun listen(observer: LifecycleObserver) {
        if (observers.contains(observer)) {
            return
        }
        addObserver(observer)
    }

    override fun addObserver(observer: LifecycleObserver) {
        super.addObserver(observer)
        observers.add(observer)
    }

    override fun removeObserver(observer: LifecycleObserver) {
        if (observers.contains(observer)) {
            super.removeObserver(observer)
            observers.remove(observer)
        }
    }

    fun release() {
        if (observers.isNotEmpty()) {
            observers.forEach {
                super.removeObserver(it)
            }
            observers.clear()
        }
    }

}